package com.blue.integration.serve.netpopo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.blue.core.http.HttpException;
import com.blue.core.util.FileUtil;
import com.blue.core.util.JsonUtil;
import com.blue.integration.serve.IdentityCard;
import com.blue.integration.serve.IdentityCardClient;
import com.blue.integration.serve.OcrException;
import org.apache.http.Header;
import org.apache.http.message.BasicHeader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * 杭州网尚OCR身份证识别
 *
 * @author zhengjin
 * @since 1.0 2018年07月05日
 */
public class NetpopoIndentityCardClient extends AbstractOcrClient implements IdentityCardClient
{
	private static Logger logger = LoggerFactory.getLogger(NetpopoIndentityCardClient.class);

	public NetpopoIndentityCardClient()
	{
	}

	@Override
	public IdentityCard ocr(IdentityCard.Side side, File file) throws OcrException
	{
		Assert.notNull(file, "身份证文件不能为空");
		try
		{
			FileInputStream fis = new FileInputStream(file);
			return this.ocr(side, fis);
		}
		catch (FileNotFoundException e)
		{
			throw new OcrException("身份证文件不存在：" + file.getAbsolutePath());
		}
	}

	@Override
	public IdentityCard ocr(IdentityCard.Side side, InputStream is) throws OcrException
	{
		Assert.notNull(side, "身份证正面或反面不能为空");
		Assert.notNull(is, "身份证文件输入流不能为空");
		if (side == IdentityCard.Side.BACK)
		{
			throw new OcrException("不支持反面识别");
		}

		String imgBase64 = null;
		try
		{
			imgBase64 = FileUtil.toBase64(is);
		}
		catch (IOException e)
		{
			logger.error("读取身份证文件失败：", e);
			throw new OcrException("读取身份证文件失败");
		}
		if (imgBase64 == null || imgBase64.isEmpty())
		{
			throw new OcrException("读取身份证文件失败");
		}

		Header authHeader = new BasicHeader("Authorization", "APPCODE " + appCode);
		Header contentTypeHeader = new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

		Map<String, Object> param = new HashMap<>();
		param.put("pic", imgBase64);
		String result = null;
		try
		{
			logger.debug("参数：{}", param);
			result = httpInvoker.post(url + "?isportrait=1&typeid=2", param, authHeader, contentTypeHeader);
			logger.info("结果：{}", result);
		}
		catch (HttpException | IOException e)
		{
			logger.error("身份证识别失败：", e);
			throw new OcrException("身份证识别失败");
		}
		if (result == null || result.isEmpty())
		{
			throw new OcrException("身份证识别失败");
		}

		JSONObject object = JSON.parseObject(result);
		String status = object.getString("status");
		String msg = object.getString("msg");
		if (!"0".equals(status))
		{
			throw new OcrException("身份证识别失败：" + msg);
		}

		NetPopoIdCard idCard = object.getObject("result", NetPopoIdCard.class);
		IdentityCard card = idCard.toIdentityCard();
		logger.debug("对象：{}", JsonUtil.encode(card));
		return card;
	}
}
